﻿/***************************************************
 * File name: ShoppingCart.cs 
 * Author: Team A
 * Change Log: Please see SVN repository: http://test-project-drew1.googlecode.com/svn/trunk/
 * Date: December 2013
 * Description: See <summary> tab below
 * *************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.Entity;
using System.Web;
using System.Web.Mvc;
using WSCeCommerce.Domain;
using WSCeCommerce.Helpers;
using WSCeCommerceWeb.Helpers;
using System.Text;


namespace WSCeCommerceWeb.Models
{

    /// <summary>
    /// Represents a virtual shopping cart. This class is intended to be stored in user's session on the server and maintain a list of items and quantities.
    /// </summary>
    public partial class ShoppingCart
    {
        private List<SaleItem> _items = new List<SaleItem>();

        string ShoppingCartId { get; set; }

        public const string CartSessionKey = "CartId";
        private const string SESSION_CART_KEY = "ShoppingCart";

        /// <summary>
        /// Get the current cart from the user's session
        /// </summary>
        /// <param name="context">HttpContext to get the session from</param>
        public static ShoppingCart GetCart(HttpContextBase context)
        {

            //Find the cart in the session
            ShoppingCart cart = context.Session[SESSION_CART_KEY] as ShoppingCart;

            //If the shopping cart does not exist than create and store one.
            if (cart == null)
            {
                cart = new ShoppingCart();
                context.Session[SESSION_CART_KEY] = cart;
            }

            return cart;
       
        }

        /// <summary>
        ///  Helper method to simplify shopping cart calls
        /// </summary>
        /// <param name="controller">Controller to get the session object from</param>
         public static ShoppingCart GetCart(Controller controller)
        {
            return GetCart(controller.HttpContext);
        }

         public int UpdateCart(int id, int quantity)
         {
             SaleItem cartItem = _items.Where(item => item.Item.ItemId == id).FirstOrDefault();

             cartItem.Quantity = quantity;

             return cartItem.Quantity;
         }

        /// <summary>
        /// Add an item to the cart
        /// </summary>
        /// <param name="newItem">item to be added. if the item already exists the quantity will be increased</param>

    
        
        public int AddToCart(Item newItem)
        {

            // Find an existing item
            SaleItem cartItem = _items.Where(item => item.Item.ItemId == newItem.ItemId).FirstOrDefault();

            // If the item doesn't exist than add it
            if (cartItem == null)
            {
                // Create a new cart item if no cart item exists
                cartItem = new SaleItem
                {
                   Item = newItem,
                    Quantity = 1,
                    Price = newItem.Price
                };
                _items.Add(cartItem);
            }
            else
            {
                // If the item does exist in the cart, then add one to the quantity
                cartItem.Quantity++;
            }

            return cartItem.Quantity;
        }

        /// <summary>
        /// Remove an item from the card
        /// </summary>
        /// <param name="id">Item id to be removed</param>
        /// <returns>number of items remaining</returns>
        public int RemoveFromCart(int id)
        {
            // Get the cart
            var cartItem = _items.Find(item => item.Item.ItemId == id);
            int itemCount = 0;

            if (cartItem != null)
            {
                if (cartItem.Quantity > 1)
                {
                    cartItem.Quantity--;
                    itemCount = cartItem.Quantity;
                }
                else
                {
                    _items.Remove(cartItem);
                }

            }

            return itemCount;
        }

        /// <summary>
        /// Empty the cart's contents
        /// </summary>
        public void EmptyCart()
        {
            _items.Clear();
        }

        /// <summary>
        /// Retrieve all items in the cart
        /// </summary>
        /// <returns></returns>
        public List<SaleItem> GetCartItems()
        {
            return _items;
        }

        /// <summary>
        /// Get the count of items in the cart
        /// </summary>
        /// <returns></returns>
        public int GetCount()
        {
            return _items == null ? 0 : _items.Count;
        }

        /// <summary>
        /// Sum up the order
        /// </summary>
        /// <returns>Sum of the shopping cart so far sum(Item.Quantity * item.price)</returns>
        public float GetTotal()
        {
            if (_items == null)
            {
                return 0;
            }
            else
            {
                return _items.Sum(item => item.Price * item.Quantity);
            }
        }

      
        //Not used
        public int CreateOrder(Sale order)
        {
            float orderTotal = 0;

            var cartItems = GetCartItems();

            // Iterate over the items in the cart, adding the order details for each
            foreach (var item in cartItems)
            {
                //JOE
                //var orderDetail = new OrderDetail
                //{
                //    ItemId = item.Item_ItemId,
                //    OrderId = order.SaleId,
                //    UnitPrice = Convert.ToDecimal(item.Price),
                //    Quantity = item.Quantity
                //};

                // Set the order total of the shopping cart
                //orderTotal += (item.Quantity * item.Price);

                //JOE
                // _db.OrderDetail.Add(orderDetail);

            }

            // Set the order's total to the orderTotal count
            order.Total = orderTotal;

            // Save the order
            //_db.SaveChanges();

            // Empty the shopping cart
            EmptyCart();

            // Return the OrderId as the confirmation number
            return order.SaleId;
        }

        // We're using HttpContextBase to allow access to cookies.
        //Npt used
        public string GetCartId(HttpContextBase context)
        {
            if (context.Session[CartSessionKey] == null)
            {
                if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))
                {
                    context.Session[CartSessionKey] = context.User.Identity.Name;
                }
                else
                {
                    // Generate a new random GUID using System.Guid class
                    Guid tempCartId = Guid.NewGuid();

                    // Send tempCartId back to client as a cookie
                    context.Session[CartSessionKey] = tempCartId.ToString();
                }
            }

            return context.Session[CartSessionKey].ToString();
        }

        // When a user has logged in, migrate their shopping cart to
        // be associated with their username
        
        // Not needed because a cart is associated to a session, not user id
        public void MigrateCart(int userId)
        {
           // var shoppingCart = _db.SaleItems.Where(c => c.SaleItemId.ToString() == ShoppingCartId);

            //foreach (var item in shoppingCart)
            //{

            //    item.SaleItemId = userId;
            //}
            //_db.SaveChanges();
        }
    }
}